var BinaryTree = function(){
	var head;
	
	this.add = function(nodeValue){
		if(!head){
			head = new Node("a","z",nodeValue);
		} else {
			head.add(nodeValue);
		}
	}
	
	this.print = function(){
		if(head) return head.print();
		return "";
	};
};

var Node = function(valueFrom, valueTo, nodeValue){
	var left;
	var right;
	
	var from = valueFrom.toUpperCase();
	var to = valueTo.toUpperCase();
	var middle = HalfString.getMiddle(from, to);
	
	var value = nodeValue;
	
	var addChild = function(nodeValue){
		if(nodeValue.getValue().toUpperCase() <= middle){
			if(left){
				left.add(nodeValue);
			} else {
				left = new Node(from, middle, nodeValue);
			}
		} else {
			if(right){
				right.add(nodeValue);
			} else {
				right = new Node(middle, to, nodeValue);
			}
		}
	};
	
	this.add = function(nodeValue){
		console.log(from + "-" + to + ", " + nodeValue.getValue());
		if(value.getValue() == nodeValue.getValue()){
			//var newList = value.getList().or(nodeValue.getList());
			//value.setList(newList);
			return;
		}
		addChild(nodeValue);
	};
	
	this.print = function(idt){
		idt = idt || "";
		
		var sp = " ";
		
		var text = "";
		text += "{\n";
		text += idt + sp + "range: " + from + " - " + middle + " - " + to + "\n";
		if(value) text += idt + sp + "value: " + value.getValue() + "\n";
		if(left) text += idt + sp + "left: " + left.print(idt+sp);
		if(right) text += idt + sp + "right: " + right.print(idt+sp);
		text += idt + "}\n";
		return text;
	};
	
};

var NodeValue = function(val, lis){
	var value = val;
	var list = lis;
	
	this.getValue = function(){
		return value;
	};
	
	this.getList = function(){
		return list;
	};
	
	this.setList = function(newList){
		list = newList;
	};
};

var HalfString = new function(){
	
	var findHalf = function(a, b){
		var half = [];
	
		var sA;
		var sB;
		
		while(a.length < b.length) a += "@";
		while(b.length < a.length) b += "@";
		sA = a.toUpperCase();
		sB = b.toUpperCase();
		
		var add = 0;
		for(var i = 0; i < sA.length; i++){
			var number = ((sA.charCodeAt(i) - 64) + (sB.charCodeAt(i) - 64)) / 2.0;
			number += add;
			add = (number - Math.floor(number) != 0)? 13 : 0;
			half.push(Math.floor(number));
		}
		if(add == 13){
			half.push(13);
		}
		for(var i = 0; i < half.length;){
			if(half[i] > 26){
				half[i] -= 26;
				if(i > 0){
					half[i-1] += 1;
					i--;
				}
			} else {
				i++;
			}
		}
		return half;
	};
	
	this.getMiddle = function(a, b){
		var half = findHalf(a, b);
		var s = "";
		for(var i in half) s += String.fromCharCode(half[i]+64);
		return s.replace(/@/g,"");
	};
	
};